import axios from 'axios'
import {Message} from 'element-ui'

/**
 * 默认30S请求超时
 */
axios.defaults.timeout = 30000;

// 添加请求拦截器
window.axiosPromiseCancel = []; // 请求集合
axios.interceptors.request.use(config => {
    return config
}, error => {
    Promise.reject(error)
});

// 添加响应拦截器
axios.interceptors.response.use(
    response => {
        response.cancelToken = new axios.CancelToken((cancel) => {
            window.axiosPromiseCancel.push(cancel)
        });
        return response.data
    },
    error => {
        // 错误处理
        Message({
            message: error.message,
            type: 'error',
            duration: 5 * 1000
        });
        return Promise.reject(error)
    }
);

/**
 * get请求
 * @param {String} url 请求地址
 * @param {Object} params 请求参数
 */
export function get(url, params) {
    return new Promise((resolve, reject) => {
        axios.get(url, {params}).then(res => {
            resolve(res);
        }).catch(err => {
            reject(err)
        })
    });
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 * @param {Object} config [请求时携带的配置]
 */
export function post(url, params, config) {
    return new Promise((resolve, reject) => {
        axios.post(url, params, config).then(res => {
            resolve(res);
        }).catch(err => {
            reject(err)
        })
    });
}
